<?php


namespace app\api\controller;


use think\Controller;
use think\Db;
use think\Exception;
use think\Session;

class Upload extends Controller
{
    public function request_post($url = '', $param = '') {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        $curl = curl_init();//初始化curl
        curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($curl);//运行curl
        curl_close($curl);
        return $data;
    }


    //调用人脸识别
    public function fance($access_token,$bodys){
        $token =$access_token;
        $url = 'https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=' . $token;
        $res = $this->request_post($url, $bodys);
        $res = json_decode($res,true);
        return $res;
    }


    public function baiApi(){
        $url = 'https://aip.baidubce.com/oauth/2.0/token';
        //$url = 'https://aip.baidubce.com/oauth/2.0/token';
        $post_data['grant_type']       = 'client_credentials';
        $post_data['client_id']      = '7sRu0qPIE2Qf2SPuDDPeUhm9';
        $post_data['client_secret'] = 'UnDW0ipU7UjDh7eznGq7Yy1XFH6wd9af';
        $o = "";
        foreach ( $post_data as $k => $v )
        {
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);
        $res = $this->request_post($url, $post_data);
        $res = json_decode($res,true);
        return $res;
    }


    //百度API人脸识别
    public function baiduApi(){
        $thumb = "https://community.zicmg.com/upload/platform1/202011/bd225082e70de0200c32af094f56e006.png";
        //$thumb = "http://" . $_SERVER['HTTP_HOST'] . $filename;
        //调用百度Api
        $res = $this->baiApi();
        if(empty($res['access_token'])){
//            $image_path = ROOT_PATH . 'public' . DS . $filename;
//            unlink($image_path);
            $black['code'] = 202;
            $black['msg'] = "上传失败";
            return json_encode($black);
        }
        $bodys['image'] = $thumb;
        $bodys['image_type'] = "URL";
        $bodys['face_field'] = "faceshape,facetype";
        $bodys = json_encode($bodys);
        $fance = $this->fance($res['access_token'],$bodys);

        if(!empty($fance['error_code'])){
//            $image_path = ROOT_PATH . 'public' . DS . $filename;
//            unlink($image_path);
            $black['code'] = 202;
            $black['msg'] = "请上传人脸头像";
            return json_encode($black);
        }else{
           if($fance['result']['face_num']>1){
               $black['code'] = 202;
               $black['msg'] = "请上传单张人脸头像";
               return json_encode($black);
           }
            $result = $fance['result']['face_list'][0];
            if($result['face_type']['type'] != 'human' && $result['face_type']['probability']<0.8){
//                $image_path = ROOT_PATH . 'public' . DS . $filename;
//                unlink($image_path);
                $black['code'] = 202;
                $black['msg'] = "请重新上传人脸";

                dump($black);die;
                return json_encode($black);die;
            }
        }
    }


    //人脸上传
    public function js_upload()
    {
        $file = $_FILES;
        if (count($file) > 0) {
            $appid = $_GET['appid'];
            $thisWechat = Db::name("config")->where(['xcx_appid'=>$appid])->find();
            $files = $this->request->file('file');//获取图片
            if (empty($file)) {
                throw new Exception("请选择上传文件");
            }
            $type = $this->file_format($_FILES['file']['name']);
            if($type==6){
                throw new Exception("上传文件格式有误");
            }
            $info = $files->move(ROOT_PATH . 'public' . DS . 'upload'.DS."platform".$thisWechat['id']);
            $filename = DS . 'upload' . DS ."platform".$thisWechat['id'].DS. $info->getSaveName();
            //图片压缩
            /*if($type<=3){
                //图片压缩
                $this->compressedImage(ROOT_PATH . 'public' . $filename,ROOT_PATH . 'public' . $filename);
            }*/
            $thumb = "http://" . $_SERVER['HTTP_HOST'] . $filename;

            //调用百度Api
            $res = $this->baiApi();
            if(empty($res['access_token'])){
                $image_path = ROOT_PATH . 'public' . DS . $filename;
                unlink($image_path);
                $black['code'] = 202;
                $black['msg'] = "上传失败";
                return json_encode($black);die;
            }
            $bodys['image'] = $thumb;
            $bodys['image_type'] = "URL";
            $bodys['face_field'] = "faceshape,facetype";
            $bodys = json_encode($bodys);
            $fance = $this->fance($res['access_token'],$bodys);

            if(!empty($fance['error_code'])){
                $image_path = ROOT_PATH . 'public' . DS . $filename;
                unlink($image_path);
                $black['code'] = 202;
                $black['msg'] = "请上传人脸头像";
                return json_encode($black);die;
            }else{
                if($fance['result']['face_num']>1){
                    $black['code'] = 202;
                    $black['msg'] = "请上传单张人脸头像";
                    return json_encode($black);
                }
                $result = $fance['result']['face_list'][0];
                if($result['face_type']['type'] != 'human' && $result['face_type']['probability']<0.8){
                    $image_path = ROOT_PATH . 'public' . DS . $filename;
                    unlink($image_path);
                    $black['code'] = 202;
                    $black['msg'] = "请重新上传人脸";
                    return json_encode($black);die;
                }
            }
            //调用百度Api end

            if ($filename) {
                $data['code'] = 0;
                $data['msg'] = "上传成功";
                $data['avatar'] = $filename;
                $data['thumb'] = $thumb;
            }else{
                $this->error();
                $data['code'] = 202;
                $data['msg'] = "上传失败";
            }
            return json_encode($data);
        }
    }


    /**
     * 图片上传
     */
    public function upload()
    {
        $file = $_FILES;
        if (count($file) > 0) {
            //$thisWechat = Session::get("thisWechat");
            $userid = empty($_GET['userid'])?0:$_GET['userid'];
            $appid = empty($_GET['appid'])?"wx2cd7120426ce7ee6":$_GET['appid'];
            $thisWechat = Db::name("config")->where(['xcx_appid'=>$appid])->find();
            $files = $this->request->file('file');//获取图片
            if (empty($file)) {
                throw new Exception("请选择上传文件");
            }
            $type = $this->file_format($_FILES['file']['name']);
            if($type==6){
                throw new Exception("上传文件格式有误");
            }
            if($type<=3){
//                if($_FILES['file']['size']>1024000){
//                    throw new Exception("图片大小超过限制，请上传1M以内的图片");
//                }
            }
            $ContentType = $_FILES['file']['type'];
            $info = $files->move(ROOT_PATH . 'public' . DS . 'upload'.DS."platform".$thisWechat['id']);

            $filename = DS . 'upload' . DS ."platform".$thisWechat['id'].DS. $info->getSaveName();
            //图片压缩
            if($type<=3){
                //图片压缩
                $this->compressedImage(ROOT_PATH . 'public' . $filename,ROOT_PATH . 'public' . $filename);
            }
            $real_path = $info->getRealPath();
            $size = 0;
            if(file_exists($real_path)){
                clearstatcache();
                $size = filesize($real_path);
            }
            //保存值腾讯云
            $src = $this->putObject(ROOT_PATH . 'public' . $filename,-2,$size,$type,$ContentType,$userid,$thisWechat['id']);

            if ($src) {
                if(file_exists($real_path)){
                    unset($info);
                    unlink($real_path);  //删除文件
                }
                $data['code'] = 0;
                $data['msg'] = "上传成功";
                $data['avatar'] = $src;
                $data['thumb'] = $src;
            }else{
                $this->error();
                $data['code'] = 202;
                $data['msg'] = "上传失败";
            }
            return json_encode($data);
        }
    }


    function file_format($file)
    {
        // 取文件后缀名
        $str = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        //strtolower 将所有字符转换为小写
        //pathinfo 获取文件信息，详细用法见下面我的补充
        // 文档格式
        $text = array('doc','docx','ppt','xls','xlsx','wps','txt','pdf','word');
        // 压缩格式
        $zip = array('rar', 'zip', 'tar',  'jar',  '7-zip', 'arj', 'gzip','tz');
        // 图片格式
        $image = array('jpg', 'png', 'ico', 'bmp', 'gif', 'tif',  'bmp',  'jpeg', 'svg');
        $video = array('mp4');
        //音频格式
        $audio = array('mp3');
        // 匹配不同的结果
        if (in_array($str, $text)) {
            return 1;
        } elseif (in_array($str, $zip)) {
            return 2;
        } elseif (in_array($str, $image)) {
            return 3;
        } elseif (in_array($str, $video)) {
            return 4;
        } elseif (in_array($str, $audio)) {
            return 5;
        } else {
            return 6;
        }
    }

    /**
     * desription 压缩图片
     * @param sting $imgsrc 图片路径
     * @param string $imgdst 压缩后保存路径
     */
    public function compressedImage($imgsrc, $imgdst) {
        list($width, $height, $type) = getimagesize($imgsrc);
        $new_width = $width;//压缩后的图片宽
        $new_height = $height;//压缩后的图片高
        if($width >= 600){
            $per = 600 / $width;//计算比例
            $new_width = $width * $per;
            $new_height = $height * $per;
        }
        switch ($type) {
            case 1:
                $giftype = check_gifcartoon($imgsrc);
                if ($giftype) {
                    header('Content-Type:image/gif');
                    $image_wp = imagecreatetruecolor($new_width, $new_height);
                    $image = imagecreatefromgif($imgsrc);
                    imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                    //90代表的是质量、压缩图片容量大小
                    imagejpeg($image_wp, $imgdst, 75);
                    imagedestroy($image_wp);
                    imagedestroy($image);
                }
                break;
            case 2:
                header('Content-Type:image/jpeg');
                $image_wp = imagecreatetruecolor($new_width, $new_height);
                $image = imagecreatefromjpeg($imgsrc);
                imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                //90代表的是质量、压缩图片容量大小
                imagejpeg($image_wp, $imgdst, 75);
                imagedestroy($image_wp);
                imagedestroy($image);
                break;
            case 3:
                header('Content-Type:image/png');
                $image_wp = imagecreatetruecolor($new_width, $new_height);
                $image = imagecreatefrompng($imgsrc);
                imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                //90代表的是质量、压缩图片容量大小
                imagejpeg($image_wp, $imgdst, 75);
                imagedestroy($image_wp);
                imagedestroy($image);
                break;
        }
    }


    //腾讯云上传
    public function putObject($local_path,$group_id=0,$size=0,$type=0,$ContentType='image/jpeg',$userid=0,$uniacid=0){
        require ROOT_PATH."extend/cos/vendor/autoload.php";//引入PHPExcel加载文件
        $secretId = "AKIDDAqOnvZfYeZDbrjYzFMD4ezhhXiYKUYK"; //"云 API 密钥 SecretId";
        $secretKey = "zi9JM6jG6gz3vb3E9tR4RbW9bnCOKzRf"; //"云 API 密钥 SecretKey";
        $region = "ap-nanjing"; //设置一个默认的存储桶地域
        $cosClient = new \Qcloud\Cos\Client(
            array(
                'region' => $region,
                'schema' => 'http', //协议头部，默认为http
                'credentials'=> array(
                    'secretId'  => $secretId ,
                    'secretKey' => $secretKey)));


        $platform = "platform".$uniacid; //平台
        $time = date("Y-m-d"); //日期
        $name = md5(microtime()).".".substr(strrchr($local_path, '.'), 1); //文件名


        try {
            $result = $cosClient->putObject(array(
                'Bucket' => 'tickets-1253901423', //格式：BucketName-APPID
                'Key' =>$platform.'/' .$time.'/'.$name,
                'Body' => fopen($local_path, 'rb'),
                "ContentType" => $ContentType
            ));
            // 请求成功
            $array = (array)$result;
            foreach ($array as $key => $value) {
                $src = "https://".$value['Location'];
                $ETag = $value['ETag'];
            }
            //保存图片信息到数据库
            $data['group_id'] = $group_id;
            $data['path'] = $src;
            $data['ETag'] = $ETag;
            $data['name'] = $name;
            $data['size'] = $size;
            $data['insertdata'] = date("Y-m-d");
            $data['add_id'] = $userid;
            $data['addtime'] = time();
            $data['table'] = 'admin_fans';
            $data['uniacid'] = $uniacid;
            $data['type'] = $type;
            $data['ContentType'] = $ContentType;
            Db::name("upload_images")->insert($data);
            return $src;
        } catch (\Exception $e) {
            //请求失败
            throw new Exception("上传有误");
        }
    }


    //删除图片
    public function delImage(){
        $image = $_POST['image'];
        //删除文件
        @unlink($_SERVER['DOCUMENT_ROOT'].$image);
        $black['code'] = 0;
        $black['msg'] = "删除成功";
        return json_encode($black);
    }

}